package com.cmdi.log.event;

import com.cmdi.domain.R;
import com.cmdi.domain.SysUserLog;
import com.cmdi.feign.RemoteLogServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Description: LogEventListener
 * @Author: gaozb
 */
@Component
public class LogEventListener {

    @Autowired
    private RemoteLogServiceFeignClient remoteLogServiceFeignClient;

    @Async
    @EventListener(LogEvent.class)
    public void handleEvent(LogEvent logEvent) {
        SysUserLog sysUserLog = logEvent.getSysUserLog();

//        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
//            RequestContextHolder.setRequestAttributes(requestAttributes, true);
//            ResponseEntity<String> log = remoteLogServiceFeignClient.getLog();
//            System.out.println(log.getBody());
//            System.out.println(log.getStatusCode());
//        });

        ResponseEntity<R> log = remoteLogServiceFeignClient.saveLog(sysUserLog, logEvent.getToken());
        HttpStatus statusCode = log.getStatusCode();
        R body = log.getBody();
        if(statusCode == HttpStatus.NOT_ACCEPTABLE
                && body.getCode() == -1) {
            //经过feign fallback处理后
            throw new RuntimeException("保存日志错误");
        }

        if(statusCode != HttpStatus.OK) {
            throw new RuntimeException("调用服务未知错误");
        }
//        if(logEvent.getToken() != null) {
//            ResponseEntity<R> log = remoteLogServiceFeignClient.saveLog(sysUserLog, logEvent.getToken());
//            System.out.println(log.getBody().getData());
//            System.out.println(log.getStatusCode());
//        } else {
//            //无需token的请求，直接控制台打印。因为saveLog要求的权限是登录
//            System.out.println(sysUserLog);
//        }

    }
}